package com.example.chamberlainserver.Service.impl;

import com.example.chamberlainserver.Entry.DormTrippingRecord;
import com.example.chamberlainserver.Entry.User;
import com.example.chamberlainserver.Service.DormTrippingRecordService;
import com.example.chamberlainserver.Vo.Request.DormTripping.DormTrippingRecordQuery;
import com.example.chamberlainserver.dto.PageResult;
import com.example.chamberlainserver.mapper.DormTrippingRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import com.example.chamberlainserver.security.JwtTokenUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 宿舍跳闸记录服务实现类
 */
@Service
public class DormTrippingRecordServiceImpl implements DormTrippingRecordService {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private static final Logger logger = LoggerFactory.getLogger(DormTrippingRecordServiceImpl.class);

    @Autowired
    private DormTrippingRecordMapper dormTrippingRecordMapper;

    @Override
    @Transactional
    public DormTrippingRecord addRecord(DormTrippingRecord record) {
        // 验证记录信息
        validateRecord(record);
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        record.setCreateTime(now);
        record.setUpdateTime(now);
        
        // 如果未设置处理状态，默认为未处理
        if (record.getIsHandled() == null) {
            record.setIsHandled(false);
        }
        
        // 插入记录
        dormTrippingRecordMapper.insertRecord(record);
        
        // 返回插入后的记录信息（包含自增ID）
        return record;
    }

    @Override
    @Transactional
    public DormTrippingRecord updateRecord(DormTrippingRecord record) {
        // 验证记录ID
        if (record.getId() == null) {
            throw new IllegalArgumentException("记录ID不能为空");
        }
        
        // 检查记录是否存在
        DormTrippingRecord existingRecord = dormTrippingRecordMapper.getRecordById(record.getId());
        if (existingRecord == null) {
            throw new IllegalArgumentException("记录不存在");
        }
        
        // 设置更新时间
        record.setUpdateTime(LocalDateTime.now());

        // 获取当前登录用户ID
        Integer currentUserId = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            // 从请求头中获取JWT Token
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String authorizationHeader = request.getHeader("Authorization");
            if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                String jwtToken = authorizationHeader.substring(7);
                currentUserId = jwtTokenUtil.getUserIdFromToken(jwtToken);
            }
        }

        if (currentUserId == null) {
            throw new IllegalArgumentException("无法获取当前登录用户ID，请重新登录。");
        }
        record.setUpdatedByUserId(currentUserId);

        // 打印日志，用于调试
        logger.info("更新记录时，获取到的 updatedByUserId: {}", record.getUpdatedByUserId());

        System.out.println("record" + record);

        // 更新记录
        dormTrippingRecordMapper.updateRecord(record);
        
        // 返回更新后的记录信息
        return dormTrippingRecordMapper.getRecordById(record.getId());
    }

    @Override
    @Transactional
    public boolean deleteRecord(Integer id) {
        // 验证记录ID
        if (id == null) {
            throw new IllegalArgumentException("记录ID不能为空");
        }
        
        // 检查记录是否存在
        DormTrippingRecord existingRecord = dormTrippingRecordMapper.getRecordById(id);
        if (existingRecord == null) {
            throw new IllegalArgumentException("记录不存在");
        }
        
        // 删除记录
        return dormTrippingRecordMapper.deleteRecord(id) > 0;
    }

    @Override
    public DormTrippingRecord getRecordById(Integer id) {
        // 验证记录ID
        if (id == null) {
            throw new IllegalArgumentException("记录ID不能为空");
        }
        
        // 查询记录
        return dormTrippingRecordMapper.getRecordById(id);
    }

    @Override
    public List<DormTrippingRecord> getAllRecords() {
        return dormTrippingRecordMapper.getAllRecords();
    }

    @Override
    public List<DormTrippingRecord> getRecordsByDormitoryNum(String dormitoryNum) {
        // 验证宿舍号
        if (dormitoryNum == null || dormitoryNum.trim().isEmpty()) {
            throw new IllegalArgumentException("宿舍号不能为空");
        }
        
        // 查询记录
        return dormTrippingRecordMapper.getRecordsByDormitoryNum(dormitoryNum.trim());
    }

    @Override
    public List<DormTrippingRecord> getRecordsByClassName(String className) {
        // 验证班级名称
        if (className == null || className.trim().isEmpty()) {
            throw new IllegalArgumentException("班级名称不能为空");
        }
        
        // 查询记录
        return dormTrippingRecordMapper.getRecordsByClassName(className.trim());
    }

    @Override
    public List<DormTrippingRecord> getRecordsByCounselor(String counselor) {
        // 验证辅导员姓名
        if (counselor == null || counselor.trim().isEmpty()) {
            throw new IllegalArgumentException("辅导员姓名不能为空");
        }
        
        // 查询记录
        return dormTrippingRecordMapper.getRecordsByCounselor(counselor.trim());
    }

    @Override
    public List<DormTrippingRecord> getRecordsByHandleStatus(Boolean isHandled) {
        // 验证处理状态
        if (isHandled == null) {
            throw new IllegalArgumentException("处理状态不能为空");
        }
        
        // 查询记录
        return dormTrippingRecordMapper.getRecordsByHandleStatus(isHandled);
    }

    @Override
    public PageResult<DormTrippingRecord> getPagedRecordList(DormTrippingRecordQuery recordQuery) {
        // 参数校验
        if (recordQuery == null) {
            throw new IllegalArgumentException("查询参数不能为空");
        }
        
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        
        // 分页参数
        Integer current = recordQuery.getCurrent();
        Integer pageSize = recordQuery.getPageSize();
        if (current == null || current < 1) {
            current = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        params.put("offset", (current - 1) * pageSize);
        params.put("limit", pageSize);
        
        // 查询条件
        if (recordQuery.getDormitoryNum() != null && !recordQuery.getDormitoryNum().trim().isEmpty()) {
            params.put("dormitoryNum", recordQuery.getDormitoryNum().trim());
        }
        
        if (recordQuery.getStudentName() != null && !recordQuery.getStudentName().trim().isEmpty()) {
            params.put("studentName", recordQuery.getStudentName().trim());
        }
        
        if (recordQuery.getClassName() != null && !recordQuery.getClassName().trim().isEmpty()) {
            params.put("className", recordQuery.getClassName().trim());
        }
        
        if (recordQuery.getCounselor() != null && !recordQuery.getCounselor().trim().isEmpty()) {
            params.put("counselor", recordQuery.getCounselor().trim());
        }
        
        if (recordQuery.getIsHandled() != null) {
            params.put("isHandled", recordQuery.getIsHandled());
        }
        
        if (recordQuery.getMinTrippingPower() != null) {
            params.put("minTrippingPower", recordQuery.getMinTrippingPower());
        }
        
        if (recordQuery.getMaxTrippingPower() != null) {
            params.put("maxTrippingPower", recordQuery.getMaxTrippingPower());
        }
        
        // 日期范围
        if (recordQuery.getStartDate() != null && !recordQuery.getStartDate().trim().isEmpty() 
                && recordQuery.getEndDate() != null && !recordQuery.getEndDate().trim().isEmpty()) {
            params.put("startDate", recordQuery.getStartDate().trim());
            params.put("endDate", recordQuery.getEndDate().trim());
        }
        
        // 查询数据
        List<DormTrippingRecord> records = dormTrippingRecordMapper.getPagedRecordList(params);
        Long total = dormTrippingRecordMapper.getPagedRecordCount(params);
        
        // 构建分页结果
        return new PageResult<>(current, pageSize, total, records);
    }
    
    /**
     * 验证跳闸记录信息
     * @param record 跳闸记录信息
     */
    private void validateRecord(DormTrippingRecord record) {
        if (record == null) {
            throw new IllegalArgumentException("跳闸记录信息不能为空");
        }
        
        if (record.getDormitoryNum() == null || record.getDormitoryNum().trim().isEmpty()) {
            throw new IllegalArgumentException("宿舍号不能为空");
        }
        
        if (record.getStudentName() == null || record.getStudentName().trim().isEmpty()) {
            throw new IllegalArgumentException("学生姓名不能为空");
        }
        
        if (record.getClassName() == null || record.getClassName().trim().isEmpty()) {
            throw new IllegalArgumentException("班级名称不能为空");
        }
        
        if (record.getCounselor() == null || record.getCounselor().trim().isEmpty()) {
            throw new IllegalArgumentException("辅导员姓名不能为空");
        }
        
        if (record.getTrippingPower() == null) {
            throw new IllegalArgumentException("跳闸功率不能为空");
        }
        
        if (record.getTrippingTime() == null) {
            throw new IllegalArgumentException("跳闸时间不能为空");
        }
    }
}